<?php

/**
 * @copyright (c) 2011
 */
App::uses('AppModel', 'Model');

class BankUser extends AppModel {

    var $name = 'BankUser';

    public $belongsTo = array(
        'BankBranch' => array(
            'className' => 'BankBranch',
            'foreignKey' => 'bank_branch_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public $hasMany = array(
        'Transaction' => array(
            'className' => 'Transaction',
            'foreignKey' => 'bank_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'BankReportLog' => array(
            'className' => 'BankReportLog',
            'foreignKey' => 'bank_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'BankCreditAuthorization' => array(
            'className' => 'BankCreditAuthorization',
            'foreignKey' => 'bank_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'BankReversalAuthorization' => array(
            'className' => 'BankReversalAuthorization',
            'foreignKey' => 'bank_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public function save($data = null,$validate = true, $fieldList = array()) {
        $s = $this->sanitize($data);
        return parent::save($s);
    }

    function disableByUsername($username) {
        $this->updateAll(
            array('BankUser.active' => "n"),
            array('BankUser.username' => $username)
        );
    }

    function login($username = null, $password = null) {
        $modObj = ClassRegistry::init('BankFailedLogin');
        $trial_count = $modObj->getLoginFailedAttempts($username);
        if($trial_count >= 3){
            return array('status' => false, 'log-failed-attempt'=>false ,'msg' => 'Account is disabled, please contact an administrator.');
        }

        $password = md5($password);
        $result = $this->find('first', array(
            'conditions' => array('username' => $username, 'password' => $password),
            'recursive' => -1
        ));
        if ($result) {
            $active = $result['BankUser']['active'];
            if ($active == 'Disabled') { /** User is disabled, Logout */
                return array('status' => false, 'log-failed-attempt'=>false ,'msg' => 'Account is disabled, please contact an administrator.');
            } else {
                return array('status' => true, 'msg' => 'Account Verified', 'data' => $result);
            }
        }
        else {
            return array('status' => false, 'log-failed-attempt'=>true, 'msg' => 'Invalid login credentials');
        }
    }

    /**
     * This function retrieves all the users from the database tables users.
     * @name getAllUsers
     * @param void
     * @return mixed. Array containing the data retrieved.
     * @access public
     */
    function getAllUsers() {
        # fetch the data and return it.
        return $this->find('all', array('conditions' => array('deleted' => 'n'), 'recursive' => -1));
    }

    /**
     * This function retrieves the user data based upon his/her id
     * @name getUserById
     * @param string $userId string holding the user id.his parameter is defaulted to null.
     * When it is null it means that cake is going to use the ActiveRecord system to retrieve the data.
     * @return mixed. Array containing the user data.
     * @access public
     */
    function getUserById($userId = null) {
        $conditions = array(
            'BankUser.id' => $userId,
            'BankUser.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        return $this->find('first', array('conditions' => $conditions, 'recursive' => 1));
    }

    # User Data manipulation functions
    /**
     * This function retrieves the user by his login name
     * @name getUserByLoginName
     * @param string $loginName
     * @return array of data containing the login name and the user password
     * @access public
     */

    function getUserByLoginName($loginName = null) {
        # search condition
        $conditions = array(
            'BankUser.username' => $loginName,
            'BankUser.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        return $this->find('first', array('conditions' => $conditions, 'recursive' => 1));
    }


    function getUserBranch($userId = null) {
        $conditions = array(
            'BankUser.id' => $userId,
            'BankUser.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        $d =  $this->find('first', array(
            'fields'=>array('BankUser.id','BankUser.bank_branch_id'),
            'conditions' => $conditions,
            'contain'=>array('BankBranch'=>array('fields'=>array('BankBranch.id','BankBranch.branch_name','BankBranch.branch_code','BankBranch.branch_name_full')))
        ));

        return $d;
    }

}